﻿using System.Collections.Generic;
using System.Linq;
using N2;
using N2.Collections;
using N2.Details;
using N2.Edit.Trash;
using N2.Linq;

namespace AWS.N2CMS.Tags
{
    public class Tag : ContentItem
    {
        public ItemList<ContentItem> TaggedItems
        {
            get
            {
                //var linkRepository = N2.Context.Current.Resolve<INHRepository<int, LinkDetail>>();
                var items = new List<ContentItem>();
                var query = Context.Current.Query<LinkDetail>()
                    .Where(x => x.LinkedItem == this && x.EnclosingItem.VersionOf == null);
                //foreach (LinkDetail detail in linkRepository.FindAll(Expression.Eq("LinkedItem", this), Expression.IsNull("LinkedItem.VersionOf")))
                foreach (var detail in query.Where(detail => !items.Contains(detail.EnclosingItem)))
                {
                    items.Add(detail.EnclosingItem);
                }
                var trash = Context.Current.Resolve<ITrashHandler>();
                var filter = new CompositeFilter(new VisibleFilter(), new DelegateFilter(x => !trash.IsInTrash(x)));
                return new ItemList(items, filter);
            }
        }

        public int TaggedItemsCount
        {
            get { return TaggedItems.Count; }
        }

        public override string Title
        {
            set
            {
                //When the title changes (tag name), update the name because it is used to keep track of tags in lowwer case form.
                base.Name = value.ToLower();
                base.Title = value;
            }
        }
    }
}